package com.linux.huhx.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 发送邮件的工具类
 *
 * @author huhx
 * @date: 2016年12月19日 下午4:19:30
 */
public class SendMailUtils {
    public final static String EMAIL_SEND_FROM = "768012449@qq.com"; // 发送方的qq邮箱

    // 发送短信
    public static void sendMail(String to, String subject, String message) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.port", 465); // 这个需要
        props.put("mail.smtp.auth", "true");
        props.put("mail.from", EMAIL_SEND_FROM);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        Session session = Session.getInstance(props, auth);
        MimeMessage msg = new MimeMessage(session);
        Address address;
        try {
            address = new InternetAddress(EMAIL_SEND_FROM);
            msg.setFrom(address);
            msg.setRecipients(Message.RecipientType.TO, to);
            msg.setSubject(subject);
            msg.setSentDate(new Date());
//            String text = ReadFileUtil.readFromFile("G:\\Java\\JavaEE\\Program\\2016-05-15\\SpringLearn\\huhx-core\\src\\main\\resources\\config/mail-template.vm");
//            Map<String, String> map = new HashMap<>();
//            map.put("user", "linux");
//            map.put("content", "I love you, a girl");
//            String html = RegrexUtils.replaceFormMap(text, map);
            msg.setText(message, "utf-8", "html");
            Transport.send(msg);
            System.out.println(DateFormatUtils.getNowStringTime() + "：发送成功。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送邮件需要授权
    static Authenticator auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(EMAIL_SEND_FROM, "mygkyrrkkfvjbcac"); // 这里的XXXX表示授权码
        }
    };

    // 测试
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                sendMail("285490389@qq.com", "hello world", "我爱你！"); // XXXXX表示接收方的邮箱
            }
        }).start();
        System.out.println("是异步发送的吗？");
    }
}
